﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigHistorys
{
    /// <summary>
    /// 种母历史删除Handler
    /// </summary>
    public class DeletePigHistoryHandler : IRequestHandler<DeletePigHistoryCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 猪只历史
        /// </summary>
        private readonly IBaseRepository<PigHistory> pigHistoryrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeletePigHistoryHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigHistoryrepository"></param>
        /// <param name="logger"></param>
        public DeletePigHistoryHandler(IMapper mapper, IBaseRepository<PigHistory> pigHistoryrepository, ILogger<DeletePigHistoryHandler> logger)
        {
            this.mapper = mapper;
            this.pigHistoryrepository = pigHistoryrepository;
            _logger = logger;
        }
        /// <summary>
        /// 种母历史
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeletePigHistoryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var pigHistory = await(await pigHistoryrepository.GetAll()).Where(x => x.PigHistoryId == request.PigHistoryId).FirstOrDefaultAsync();
                if (pigHistory != null)
                {
                    pigHistory.IsDeleted = 1;
                    var res = await pigHistoryrepository.Update(pigHistory);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                    }
                }
                result.Msg = "种母历史删除成功";
            }
            catch (Exception ex)
            {
                result.Msg = "种母历史删除失败";
                _logger.LogError("种母历史删除失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
